package io.vector.study.springboot.api;

import com.baomidou.mybatisplus.plugins.Page;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.io.Serializable;
import java.util.List;

/**
 * Created by vector on 2017/5/10.
 */
public abstract class ApiResponse {

    private ApiResponse() {

    }

    public static Object success() {
        return data(null);
    }

    public static Object data(Object data) {
        return result(HttpStatus.OK.value(), data);
    }

    public static Object page(Page<?> page) {
        return data(PageResponse.valueOf(page));
    }

    public static Object error(int code, String error) {
        return result(HttpStatus.UNPROCESSABLE_ENTITY.value(), new ErrorResponse(code, error));
    }

    public static Object error(ApiException apiException) {
        return error(apiException.getCode(), apiException.getMessage());
    }

    private static Object result(int httpStatus, Object data) {
        return ResponseEntity.status(httpStatus).body(data);
    }

    @Getter
    @AllArgsConstructor
    public static class PageResponse implements Serializable {

        private final List<?> rows;
        private final int page;
        private final int pageSize;
        private final int total;

        public static PageResponse valueOf(Page<?> page) {
            return new PageResponse(page.getRecords(), page.getCurrent(), page.getSize(), page.getTotal());
        }

    }

    @Getter
    @AllArgsConstructor
    public static class ErrorResponse implements Serializable {

        private final int code;
        private final String error;

    }

}
